import React, { useMemo } from 'react';
import { PageHeaderWrapper } from 'hzero-boot/lib/components/Page';
import { Table, DataSet, Modal } from 'choerodon-ui/pro';
import Record from 'choerodon-ui/pro/lib/data-set/Record';
import shopDS from './stores/shopDataSet';
import CommonAdd from './components/CommonAdd';
import { CommonEdit } from './components/CommonEdit';
import { recordFunc } from './typing.d';
import ModalDetail from './components/ModalDetail';

const { Column } = Table;

const detailModalKey = Modal.key();
let create: Record | null = null;

const ShopList: React.FC = () => {

  const shopDataSet = useMemo(() => new DataSet(shopDS()), []);

  const handleModalCancel = (record: Record) => {
    if (create) {
      shopDataSet.remove(create);
      create = null;
      return;
    }
    if (record) {
      record.reset();
    }
  };

  const openDetailModal: recordFunc = (isNew, record) => {

    if (isNew) {
      create = shopDataSet.create();
    }

    Modal.open({
      key: detailModalKey,
      title: isNew ? '新增' : '编辑',
      drawer: true,
      children: (<ModalDetail record={record || shopDataSet.current} dataSet={shopDataSet} />),
      onCancel: () => handleModalCancel(record || shopDataSet.current!),
    });
  };

  const buttons = useMemo(() => {
    return [CommonAdd({
      onClick: () => openDetailModal(true),
    })];
  }, []);

  return (
    <PageHeaderWrapper title="table">
      <Table dataSet={shopDataSet} buttons={buttons}>
        <Column name="code" width={120} />
        <Column name="name" />
        <Column name="status" />
        {CommonEdit({
          onClick: openDetailModal,
        })}
      </Table>
    </PageHeaderWrapper>
  );
};

export default ShopList;